package com.oritsh.dicom.wado.controller;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.llp.LLPException;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v26.message.ORM_O01;
import ca.uhn.hl7v2.model.v26.segment.MSA;
import com.oritsh.hl7.Client;
import com.oritsh.hl7.ClientFactory;
import com.oritsh.hl7.his.model.TechApply;
import com.oritsh.hl7.his.utils.Convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-3-15
 * Time: 下午5:17
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */
@RequestMapping("/hl7")
@Controller
public class HL7Controller {

    @Autowired
    Convert convert;

    @Autowired
    ClientFactory clientFactory;

    private boolean sendTechApply(TechApply apply,boolean isDelete)
            throws IOException, HL7Exception, LLPException {
        ORM_O01 orm = convert.convetTechApply(apply, isDelete);
        try (Client client = clientFactory.createClient()) {
            Message response = client.sendAndReceive(orm);

            MSA msa = (MSA) response.get("MSA");
            String aa = msa.getMsa1_AcknowledgmentCode().encode();

            if (aa.equals("AA"))
                return true;
            else
                return false;
        }
    }

    @RequestMapping(value = "/techApply/new",
            method = {RequestMethod.POST},
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    boolean newTechApply(@RequestBody TechApply apply)
            throws IOException, HL7Exception, LLPException {
        return sendTechApply(apply,false);
    }

    @RequestMapping(value = "/techApply/cancel",
            method = {RequestMethod.POST},
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    boolean cancelTechApply(@RequestBody TechApply apply)
            throws IOException, HL7Exception, LLPException {
        return sendTechApply(apply,true);
    }
}
